package com.dhcc.core.framework.security.client.oauth2;

import java.util.regex.Pattern;

import com.github.scribejava.core.exceptions.OAuthException;
import com.github.scribejava.core.extractors.OAuth2AccessTokenJsonExtractor;
import com.github.scribejava.core.model.OAuth2AccessToken;

public class DthJsonExtractor extends OAuth2AccessTokenJsonExtractor {

    public static final Pattern STATUS_REGEX = Pattern.compile("\"status\"\\s*:\\s*\"(\\S*?)\"");

    private static class InstanceHolder {
        private static final DthJsonExtractor INSTANCE = new DthJsonExtractor();
    }

    public static DthJsonExtractor instance() {
        return DthJsonExtractor.InstanceHolder.INSTANCE;
    }

    @Override
    protected OAuth2AccessToken createToken(String accessToken, String tokenType, Integer expiresIn,
                                            String refreshToken, String scope, String response) {
        OAuth2AccessToken token = super.createToken(accessToken, tokenType, expiresIn, refreshToken,
            scope, response);
        String status = extractParameter(response, STATUS_REGEX, true);
        if (status == null || "".equals(status)) {
            throw new OAuthException(
                "There is no required status in the response of the AssessToken endpoint.");
        }
        return new DthToken(token, status);
    }
}
